package collection.map;

import org.junit.Test;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * HashMap在并发情况下进行修改元素，也会出现问题
 */
public class MapNotSafeTest {

	/**
	 * 1.hashtable是线程安全的，所有操作元素的方法都加了synchronized
	 *
	 * @throws InterruptedException
	 */
	@Test
	public void test() throws InterruptedException {
//		Map<String, String> map = new HashMap<>();
//        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
		Map<String, String> map = new ConcurrentHashMap<>();
//		Map<String, String> map = new Hashtable<>();
		for (int i = 0; i < 30; i++) {
			new Thread(() -> {
				map.put(Thread.currentThread().getName(), UUID.randomUUID().toString().substring(0
						, 8));
				System.out.println(map);
			}, String.valueOf(i)).start();
		}
		TimeUnit.SECONDS.sleep(5);
	}

}
